import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';

class SearchHistory {
  static const String _key = 'search_history';
  static const int _maxHistorySize = 10; // 最大历史记录数量

  // 获取搜索历史记录
  static Future<List<String>> getSearchHistory() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String? historyJson = prefs.getString(_key);
    if (historyJson == null || historyJson.isEmpty) {
      return [];
    }
    try {
      List<dynamic> historyList = jsonDecode(historyJson);
      return historyList.cast<String>();
    } catch (e) {
      return [];
    }
  }

  // 添加搜索历史记录
  static Future<void> addSearchHistory(String keyword) async {
    if (keyword.trim().isEmpty) return;
    
    SharedPreferences prefs = await SharedPreferences.getInstance();
    List<String> historyList = await getSearchHistory();
    
    // 如果已存在相同关键词，先移除
    historyList.remove(keyword);
    
    // 添加到列表开头
    historyList.insert(0, keyword);
    
    // 如果超过最大数量，删除最后一个
    if (historyList.length > _maxHistorySize) {
      historyList = historyList.sublist(0, _maxHistorySize);
    }
    
    // 保存到 SharedPreferences
    await prefs.setString(_key, jsonEncode(historyList));
  }

  // 清空搜索历史记录
  static Future<void> clearSearchHistory() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    await prefs.remove(_key);
  }
  
  // 删除单条搜索历史
  static Future<void> removeSearchHistory(String keyword) async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    List<String> historyList = await getSearchHistory();
    
    historyList.remove(keyword);
    
    await prefs.setString(_key, jsonEncode(historyList));
  }
} 